import json

import numpy as np
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeyEvent
from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QVBoxLayout, QLabel, QHBoxLayout
from matplotlib import pyplot as plt

import graphicMatch
import worker


def repeat_string(s, n):
    return s * n


def pad_array_to_length(arr, target_length, pad_value=0):
    pad_width = target_length - len(arr)
    if pad_width <= 0:
        return arr
    else:
        # 使用numpy.pad进行填充
        return np.pad(arr, (0, pad_width), 'constant', constant_values=pad_value)


class UI(QWidget):

    def __init__(self):
        super().__init__()
        self.endButton = None
        self.ax = None
        self.fig = None
        self.orcButton = None
        self.orcX = None
        self.orcY = None
        self.imageLabel = None
        self.imgPath = None
        self.beginButton = None

        self.worker1 = worker.Worker()
        self.worker2 = worker.Worker()
        self.worker3 = worker.Worker()
        self.worker4 = worker.Worker()

        self.size = 15
        self.x = []
        self.y = []

        self.toX = []
        self.toY = []

        # ui
        self.initUI()
        self.pltInit()

    def pltInit(self):
        self.fig = plt.figure(num=1)
        self.ax = self.fig.add_subplot(111)
        plt.xticks()
        plt.yticks()

    def initUI(self):
        self.beginButton = QPushButton('开始', self)
        self.endButton = QPushButton('暂停', self)
        clearButton = QPushButton('清空', self)
        self.beginButton.clicked.connect(self.begin)
        clearButton.clicked.connect(self.clear)
        self.endButton.clicked.connect(self.pause)

        H_Layout = QHBoxLayout()

        V_Layout = QVBoxLayout()
        V_Layout.addLayout(self.inFileUI())
        V_Layout.addSpacing(50)
        V_Layout.addWidget(self.beginButton)
        V_Layout.addWidget(self.endButton)
        V_Layout.addWidget(clearButton)

        V_Layout2 = QHBoxLayout()
        V_Layout2.addLayout(self.lstXUI())
        V_Layout2.addSpacing(50)
        V_Layout2.addLayout(self.lstYUI())

        H_Layout.addLayout(V_Layout)
        H_Layout.addSpacing(50)
        H_Layout.addLayout(V_Layout2)
        self.setLayout(H_Layout)

        self.show()

        self.xyInit()

    def inFileUI(self):

        self.orcButton = QPushButton('识别', self)
        self.orcButton.move(20, 20)
        self.orcButton.clicked.connect(self.OCR)

        floor1 = QHBoxLayout()
        floor1.addWidget(self.orcButton)
        return floor1

    def OCR(self):
        self.clear()
        self.orcButton.setEnabled(False)
        x, y = graphicMatch.match('./img.png')
        self.orcX = x
        self.orcY = y
        self.orcButton.setEnabled(True)

        for k, i in enumerate(self.orcX):
            if i:
                for m, n in enumerate(i):
                    if n:
                        self.x[k][m].setText(str(n))

        for k, i in enumerate(self.orcY):
            if i:
                for m, n in enumerate(i):
                    if n:
                        self.y[k][m].setText(str(n))

    def xyInit(self):
        with open('list.json', 'r') as file:
            data = json.load(file)
            self.toX = data['x']
            self.toY = data['y']

        for k, i in enumerate(self.toX):
            if i:
                for m, n in enumerate(i):
                    if n:
                        self.x[k][m].setText(str(n))

        for k, i in enumerate(self.toY):
            if i:
                for m, n in enumerate(i):
                    if n:
                        self.y[k][m].setText(str(n))

    def lstXUI(self):

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel('x'))

        for j in range(0, self.size):
            t = []
            HBox = QHBoxLayout()

            for i in range(0, 5):
                spinBox = QLineEdit()
                spinBox.setFixedWidth(20)
                t.append(spinBox)
                HBox.addWidget(spinBox)
                HBox.setSpacing(10)
            self.x.append(t)
            vbox.addLayout(HBox)

        return vbox

    def lstYUI(self):

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel('y'))

        for j in range(0, self.size):
            t = []
            HBox = QHBoxLayout()

            for i in range(0, 5):
                spinBox = QLineEdit()
                spinBox.setFixedWidth(20)
                t.append(spinBox)
                HBox.addWidget(spinBox)
                HBox.setSpacing(10)
            self.y.append(t)
            vbox.addLayout(HBox)

        return vbox

    def clear(self):
        self.beginButton.setEnabled(True)
        self.endButton.setEnabled(False)

        for i in self.x:
            for j in i:
                j.clear()

        for i in self.y:
            for j in i:
                j.clear()

    def begin(self):
        self.beginButton.setEnabled(False)
        self.endButton.setEnabled(True)

        x = []
        for x1 in self.x:
            t = []
            for i in x1:
                text = i.text()
                if text:
                    t.append(int(text))
            if t:
                x.append(t)

        y = []
        for y1 in self.y:
            t = []
            for i in y1:
                text = i.text()
                if text:
                    t.append(int(text))
            if t:
                y.append(t)

        if x and y:
            with open('list.json', 'w') as file:
                json.dump({'x': x, 'y': y}, file)

        self.worker1.init(x.copy(), y.copy())
        self.worker1.start()
        self.worker1.doing = True
        self.worker1.trigger.connect(self.display)

        self.worker2.init(x.copy(), y.copy(), 'YF')
        self.worker2.start()
        self.worker2.doing = True
        self.worker2.trigger.connect(self.display)

        self.worker3.init(x.copy(), y.copy(), 'XF')
        self.worker3.start()
        self.worker3.doing = True
        self.worker3.trigger.connect(self.display)

        self.worker4.init(x.copy(), y.copy(), 'XY')
        self.worker4.start()
        self.worker4.doing = True
        self.worker4.trigger.connect(self.display)

    def pause(self):
        self.beginButton.setEnabled(True)
        self.endButton.setEnabled(False)
        self.workStop()

    def display(self, lst):
        self.beginButton.setEnabled(True)
        self.endButton.setEnabled(False)

        self.workStop()

        size = lst['size']
        data = lst['data'].copy()
        if not data:
            return
        self.pltInit()
        plt.cla()
        # plt.ion()

        if lst['type'] == 'YF':
            for k1, i in enumerate(data):
                for k2, j in enumerate(i):
                    if j == '1':
                        rect = plt.Rectangle((k2, k1), 0.95, 0.95)
                        self.ax.add_patch(rect)
        else:
            for k1, i in enumerate(data):
                for k2, j in enumerate(i):
                    if j == '1':
                        rect = plt.Rectangle((k2, size - 1 - k1), 0.95, 0.95)
                        self.ax.add_patch(rect)
        # self.fig.canvas.draw()  # 重绘图像

        plt.xticks()
        plt.yticks()
        # plt.plot()
        plt.xlim(0, size)
        plt.ylim(0, size)
        plt.show()

    def workStop(self):
        self.worker1.ShuDu.doing = False
        self.worker2.ShuDu.doing = False
        self.worker3.ShuDu.doing = False
        self.worker4.ShuDu.doing = False

        self.worker1.quit()
        self.worker2.quit()
        self.worker3.quit()
        self.worker4.quit()

    def keyReleaseEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Escape:
            self.close()
            # self.thread.quit()
